import React, { Component, Fragment } from "react";
import QueueAnim from "rc-queue-anim";
import { connect } from "react-redux";
import { Redirect, withRouter, Switch } from "react-router-dom";
import WithLoadable from '@/components/WithLoadable';
import ProtectedRoute from '@/components/ProtectedRoute';
import { Layout } from "antd";
import NavLeft from "./components/NavLeft";
import Navbar from "./components/Navbar";
import Tools from "@/utils/Tools";
import { axiosEnqueueAction } from "@/redux/action";

import "./index.scss";
const { Content } = Layout;

const routesMap = {
	"/home":WithLoadable(() => import(/* webpackChunkName:'home'*/ '@/views/Home')),
	"/system/auth": WithLoadable(() => import(/* webpackChunkName:'auth'*/ '@/views/Auth')),
	"/system/role": WithLoadable(() => import(/* webpackChunkName:'role'*/ '@/views/Role')),
	"/system/user": WithLoadable(() => import(/* webpackChunkName:'user'*/ '@/views/User')),
};
@connect(state => state,{ axiosEnqueueAction})
@withRouter
export default class Admin extends Component {

	componentWillMount(){
		this.props.history.listen(route => {
			this.props.axiosEnqueueAction(null)
		})
	}

	state = {
		collapsed: false
	};
	toggle = () => {
		this.setState({
			collapsed: !this.state.collapsed
		});
	};


	render () {
		let routes = []
		Object.keys(Tools.routesToMap(this.props.menu)).forEach(item=>{
			if(routesMap[item]){
				routes.push(<ProtectedRoute path={item} component={routesMap[item]} key={item}/>)
			}
		})
		return (
			<Fragment>
				{this.props.user.token ? (
					<Layout className="admin-layout">
						<NavLeft collapsed={this.state.collapsed} menu={this.props.menu} />
						<Layout>
							<Navbar toggle={this.toggle} />
							<Content
								className="admin-layout-content"
								key={this.props.location.pathname}
							>
								<QueueAnim type={["right", "left"]}>
									<div key={this.props.location.pathname}>
										<Switch>
											{routes}
											<Redirect to="/home" />
										</Switch>
									</div>
								</QueueAnim>
							</Content>
						</Layout>
					</Layout>
				) : (
						<Redirect
							to={{
								pathname: "/login",
								state: { from: this.props.location.pathname }
							}}
						/>
					)}
			</Fragment>
		);
	}
}
